<template>
  <div class="enhanced-tag-selector">
    <!-- 当前已选标签 -->
    <div class="selected-tags">
      <a-tag
        v-for="tag in tags"
        :key="tag"
        :closable="true"
        @close="removeTag(tag)"
        color="blue"
      >
        {{ tag }}
      </a-tag>
    </div>

    <!-- 标签搜索和选择 -->
    <div class="tag-search-container">
      <a-input
        v-model:value="searchTagText"
        placeholder="搜索或输入新标签"
        allow-clear
        @change="handleSearch"
      />

      <!-- 标签建议列表 -->
      <div v-if="showSuggestions" class="tag-suggestions">
        <div
          v-for="tag in filteredTags"
          :key="tag.id || tag"
          class="tag-item"
          @click="addTag(tag.tagName || tag)"
        >
          {{ tag.tagName || tag }}
        </div>
        <!-- 创建新标签选项 -->
        <div v-if="searchTagText && !filteredTags.some(t => t.tagName === searchTagText)" class="tag-item create-tag">
          <plus-outlined /> 创建新标签: {{ searchTagText }}
        </div>
      </div>
    </div>

    <!-- 常用标签快速选择 -->
    <div v-if="popularTags.length > 0" class="popular-tags">
      <div class="section-title">常用标签</div>
      <div class="tag-list">
        <a-tag
          v-for="tag in popularTags"
          :key="tag.id || tag"
          :color="'green'"
          :closable="false"
          @click="addTag(tag.tagName || tag)"
          class="clickable-tag"
        >
          {{ tag.tagName || tag }}
        </a-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { listAllTagsUsingGet } from '@/api/tagController.ts'

interface Props {
  tags: string[]
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:tags': [tags: string[]]
}>()

const searchTagText = ref('')
const showSuggestions = ref(false)
const allTags = ref<API.TagVO[]>([])
const popularTags = ref<API.TagVO[]>([])

// 过滤后的标签列表
const filteredTags = computed(() => {
  if (!searchTagText.value) {
    return popularTags.value.slice(0, 10) // 默认显示前10个常用标签
  }
  return allTags.value.filter(tag =>
    tag.tagName?.toLowerCase().includes(searchTagText.value.toLowerCase())
  )
})

// 添加标签
const addTag = (tagName: string | object) => {
  // 确保tagName是字符串
  const tagStr = typeof tagName === 'object'
    ? (tagName as any).tagName || JSON.stringify(tagName)
    : tagName;

  if (!tagStr) return

  // 检查标签是否已存在
  if (props.tags && props.tags.includes(tagStr)) {
    return
  }

  // 创建新的标签数组并触发更新
  const newTags = props.tags ? [...props.tags, tagStr] : [tagStr]
  emit('update:tags', newTags)

  // 清空搜索框
  searchTagText.value = ''
  showSuggestions.value = false
}

// 移除标签
const removeTag = (tagName: string) => {
  const newTags = props.tags ? props.tags.filter(tag => tag !== tagName) : []
  emit('update:tags', newTags)
}

// 处理搜索
const handleSearch = () => {
  if (searchTagText.value) {
    showSuggestions.value = true
  } else {
    showSuggestions.value = false
  }
}

// 加载所有标签
const loadAllTags = async () => {
  try {
    const res = await listAllTagsUsingGet()
    if (res.data.code === 0 && res.data.data) {
      allTags.value = res.data.data
      // 这里可以根据标签使用频率等逻辑筛选常用标签
      popularTags.value = res.data.data.slice(0, 10)
    }
  } catch (error) {
    console.error('加载标签列表失败', error)
  }
}

// 组件挂载时加载标签列表
loadAllTags()
</script>

<style scoped>
.enhanced-tag-selector {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 12px;
}

.selected-tags {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-search-container {
  position: relative;
  margin-bottom: 12px;
}

.tag-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 10;
  margin-top: 4px;
}

.tag-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.tag-item:hover {
  background-color: #f0f0f0;
}

.create-tag {
  color: #1890ff;
}

.popular-tags {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.section-title {
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 8px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.clickable-tag {
  cursor: pointer;
}
</style>
